package com.dc.docs._888_面试.concurrent._1_volatile;

import java.util.concurrent.TimeUnit;
/**
 * Description: Volatile Demo，未加 Volatile关键词修饰的场景
 * @author: gdc
 * @date: 2021/6/15
 * @version 1.0
 */
public class Volatile_1_NoAdd {

    private int number;

    /**
     * 将 number 值修改为60
     */
    public void addTo60(){
        this.number = 60;
    }

    public static void main(String[] args){
        Volatile_1_NoAdd volatileDemo = new Volatile_1_NoAdd();

        // 第一个线程将 number 值，修改为60
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "come in");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            volatileDemo.addTo60();
            System.out.println(Thread.currentThread().getName() + "update number value:" + volatileDemo.number);
        }, "AAA").start();

        //第2个线程是main线程
        while (volatileDemo.number == 0) {
            //main线程就一直等待循环，直到number的值不等于0
        }

        // 由于缺少 volatile关键字修饰，当number值修改后，未通知到其他线程，导致主线程一直处于循环等待中
        System.out.println(Thread.currentThread().getName() + " mission is over, main thread number value:" + volatileDemo.number);
    }
}
